﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using XCode;
using XCode.Configuration;

namespace NewLife.YWS.Entities
{
    /// <summary>
    /// 机器零件规格
    /// </summary>
    public partial class Machine : YWSEntityBase<Machine>
    {
        #region 对象操作
        //基类Entity中包含三个对象操作：Insert、Update、Delete
        //你可以重载它们，以改变它们的行为
        //如：
        /*
        /// <summary>
        /// 已重载。把该对象插入到数据库。这里可以做数据插入前的检查
        /// </summary>
        /// <returns>影响的行数</returns>
        public override Int32 Insert()
        {
            return base.Insert();
        }
         * */
        #endregion

        #region 扩展属性
        //TODO: 本类与哪些类有关联，可以在这里放置一个属性，使用延迟加载的方式获取关联对象

        private Customer _Customer;
        /// <summary>该机器零件规格所对应的客户</summary>
        public Customer Customer
        {
            get
            {
                if (_Customer == null && CustomerID > 0 && !Dirtys.ContainsKey("Customer"))
                {
                    _Customer = Customer.FindByKey(CustomerID);
                    Dirtys.Add("Customer", true);
                }
                return _Customer;
            }
            set { _Customer = value; }
        }
        #endregion

        #region 扩展查询
        /// <summary>
        /// 根据主键查询一个机器零件规格实体对象用于表单编辑
        /// </summary>
        /// <returns></returns>
        [DataObjectMethod(DataObjectMethodType.Select, false)]
        public static Machine FindByKeyForEdit(Int32 __ID)
        {
            Machine entity = FindByKey(__ID);
            if (entity == null)
            {
                entity = new Machine();
            }
            return entity;
        }

        /// <summary>
        /// 根据编号查找
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Machine FindByID(Int32 id)
        {
            return Find(_.ID, id);
            // 实体缓存
            //return Meta.Cache.Entities.Find(_.ID, id);
            // 单对象缓存
            //return Meta.SingleCache[id];
        }

        /// <summary>
        /// 根据名称查找
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Machine FindByName(String name)
        {
            return Find(_.Name, name);
            // 实体缓存
            //return Meta.Cache.Entities.Find(_.Name, name);
            // 单对象缓存
            //return Meta.SingleCache[name];
        }
        #endregion

        #region 高级查询
        /// <summary>
        /// 查询满足条件的记录集，分页、排序
        /// </summary>
        /// <param name="name"></param>
        /// <param name="orderClause">排序，不带Order By</param>
        /// <param name="startRowIndex">开始行，0开始</param>
        /// <param name="maximumRows">最大返回行数</param>
        /// <returns>实体集</returns>
        [DataObjectMethod(DataObjectMethodType.Select, true)]
        public static EntityList<Machine> Search(String name, String groups, String customer, String orderClause, Int32 startRowIndex, Int32 maximumRows)
        {
            return FindAll(SearchWhere(name, groups, customer), orderClause, null, startRowIndex, maximumRows);
        }

        /// <summary>
        /// 查询满足条件的记录总数，分页和排序无效，带参数是因为ObjectDataSource要求它跟Search统一
        /// </summary>
        /// <param name="name"></param>
        /// <param name="orderClause">排序，不带Order By</param>
        /// <param name="startRowIndex">开始行，0开始</param>
        /// <param name="maximumRows">最大返回行数</param>
        /// <returns>记录数</returns>
        public static Int32 SearchCount(String name, String groups, String customer, String orderClause, Int32 startRowIndex, Int32 maximumRows)
        {
            return FindCount(SearchWhere(name, groups, customer), null, null, 0, 0);
        }

        /// <summary>
        /// 构造搜索条件
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private static String SearchWhere(String name, String groups, String customer)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("1=1");

            if (!String.IsNullOrEmpty(name)) sb.AppendFormat(" And {0} like '%{1}%'", _.Name, name.Replace("'", "''"));
            if (!String.IsNullOrEmpty(groups)) sb.AppendFormat(" And {0} like '%{1}%'", _.Groupings, groups.Replace("'", "''"));
            if (!String.IsNullOrEmpty(customer))
            {
                List<Customer> list = Customer.Search(customer, null, null, null, 0, 0);
                if (list != null && list.Count > 0)
                {
                    String ids = String.Empty;
                    ids = String.Join(",", list.ConvertAll<String>(delegate(Customer c) { return c.ID.ToString(); }).ToArray());
                    sb.AppendFormat(" And {0} in ({1})", _.CustomerID, ids);
                }
                else sb.AppendFormat(" And {0}=-1", _.CustomerID);
            }

            if (sb.ToString() == "1=1")
                return null;
            else
                return sb.ToString();
        }

        /// <summary>
        /// 查询满足条件的记录总数，分页和排序无效，带参数是因为ObjectDataSource要求它跟Search统一
        /// </summary>
        /// <param name="key"></param>
        /// <param name="orderClause">排序，不带Order By</param>
        /// <param name="startRowIndex">开始行，0开始</param>
        /// <param name="maximumRows">最大返回行数</param>
        /// <returns>记录数</returns>
        [DataObjectMethod(DataObjectMethodType.Select, true)]
        public static EntityList<Machine> Search(String key, String orderClause, Int32 startRowIndex, Int32 maximumRows)
        {
            return FindAll(SearchWhere(key), orderClause, null, startRowIndex, maximumRows);
        }

        /// <summary>
        /// 查询满足条件的记录总数，分页和排序无效，带参数是因为ObjectDataSource要求它跟Search统一
        /// </summary>
        /// <param name="key"></param>
        /// <param name="orderClause">排序，不带Order By</param>
        /// <param name="startRowIndex">开始行，0开始</param>
        /// <param name="maximumRows">最大返回行数</param>
        /// <returns>记录数</returns>
        public static Int32 SearchCount(String key, String orderClause, Int32 startRowIndex, Int32 maximumRows)
        {
            return FindCount(SearchWhere(key), null, null, 0, 0);
        }

        /// <summary>
        /// 构造搜索条件
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static String SearchWhere(String key)
        {
            if (String.IsNullOrEmpty(key)) return null;
            key = key.Replace("'", "''");
            String[] keys = key.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            StringBuilder sb = new StringBuilder();
            sb.Append("1=1");

            //sb.AppendFormat(" And {0} like '%{1}%'", _.No, key.Replace("'", "''"));
            //sb.AppendFormat(" And {0} like '%{1}%'", _.Name, key.Replace("'", "''"));
            //sb.AppendFormat(" And {0} like '%{1}%'", _.Department, key.Replace("'", "''"));
            //sb.AppendFormat(" And {0} like '%{1}%'", _.Linkman, key.Replace("'", "''"));

            for (int i = 0; i < keys.Length; i++)
            {
                sb.Append(" And ");

                if (keys.Length > 1) sb.Append("(");
                Int32 n = 0;
                foreach (FieldItem item in Meta.Fields)
                {
                    if (item.Property.PropertyType != typeof(String)) continue;
                    // 只要前五项
                    if (++n > 5) break;

                    if (n > 1) sb.Append(" Or ");
                    sb.AppendFormat("{0} like '%{1}%'", item.Name, keys[i]);
                }
                if (keys.Length > 1) sb.Append(")");
            }

            if (sb.Length == "1=1".Length)
                return null;
            else
                return sb.ToString();
        }
        #endregion

        #region 扩展操作
        #endregion

        #region 业务
        #endregion
    }
}